package com.asm.slidingmenu.Backup;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.channels.FileChannel;
import java.sql.Date;
import java.text.SimpleDateFormat;

import android.app.Fragment;
import android.content.Context;
import android.os.Environment;
import android.text.format.DateFormat;
import android.widget.Toast;

public class ASM_Backup  {
	
	private Context context;
	String packageName="com.dspl.asmswd";
	String DATABASE_NAME="ASM.db";

	public ASM_Backup (Context context){
		this.context = context;
		
	}
	
	public void exportDB() {
		try {
			
			File folder = new File(Environment.getExternalStorageDirectory() + "/ASMDBbackup");
			boolean success = true;
			if (!folder.exists()) {
			    success = folder.mkdir();
			}
			if (success) {
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
			Date date = new Date(0);
			
			
		    File sd = Environment.getExternalStorageDirectory();
		    File data = Environment.getDataDirectory();

		    if (sd.canWrite()) {
		        String currentDBPath = "//data//" + packageName
		                + "//databases//" + DATABASE_NAME;
		        String backupDBPath = "//ASMDBbackup//backupname_"+dateFormat.format(date).toString()+".db"; // From SD directory.
		        File currentDB = new File(data, currentDBPath);
		        File backupDB = new File(sd, backupDBPath);

		        FileChannel src = new FileInputStream(currentDB).getChannel();
		        FileChannel dst = new FileOutputStream(backupDB).getChannel();
		        dst.transferFrom(src, 0, src.size());
		        src.close();
		        dst.close();
		        Toast.makeText(context, "Backup Successful!",Toast.LENGTH_SHORT).show();

		    }
			}else {
			    // Do something else on failure 
				Toast.makeText(context, "Backup Failed!", Toast.LENGTH_SHORT).show();
			}
				} catch (Exception e) {

			
		    Toast.makeText(context, "Backup Failed!", Toast.LENGTH_SHORT).show();

			}
		}

}
